package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.shopping.converter.ICatCategoriesConverter;
import com.cskaoyan.shopping.converter.ProductCateConverter;
import com.cskaoyan.shopping.dal.entitys.ItemCat;
import com.cskaoyan.shopping.dal.persistence.ItemCatMapper;
import com.cskaoyan.shopping.dto.AllProductCateRequest;
import com.cskaoyan.shopping.dto.AllProductCateResponse;
import com.cskaoyan.shopping.dto.ProductCateDto;
import com.cskaoyan.shopping.service.IProductCateService;
import com.cskaoyan.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建日期: 2022/04/24 14:30
 *
 * @author ChengWenqi
 */

@Slf4j
@Service
public class IProductCateServiceImpl implements IProductCateService {

    @Autowired
    ItemCatMapper itemCatMapper;

    @Autowired
    ProductCateConverter productCateConverter;

    @Override
    public AllProductCateResponse getAllProductCate(AllProductCateRequest request) {
        AllProductCateResponse response = new AllProductCateResponse();

        try {
            request.requestCheck();
            // todo:参考代码没有传入sort，先按sort_order排序
            Example example = new Example(ItemCat.class);
            example.setOrderByClause(request.getSort());
            List<ItemCat> itemCats = itemCatMapper.selectByExample(example);

            List<ProductCateDto> productCateDtos = new ArrayList<>();
            if (!CollectionUtils.isEmpty(itemCats)) {
                productCateDtos = productCateConverter.items2Dto(itemCats);
            }
            response.setProductCateDtoList(productCateDtos);
            // 设置成功响应码和响应信息
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("IProductCateServiceImpl.getAllProductCate occur Exception: " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }

        return response;
    }
}
